package master

import (
	"context"
	"encoding/json"
	"gitee.com/alone.com/go-crontab/crontab/common"
	"go.etcd.io/etcd/clientv3"
	"time"
)

type JobManager struct {
	client *clientv3.Client
	kv     clientv3.KV
	lease  clientv3.Lease
}

var G_JobMgr *JobManager

func InitJobManager() error {
	config := clientv3.Config{
		Endpoints:   G_config.EtcdEndPoints,
		DialTimeout: time.Duration(G_config.EtcdDialTimeout) * time.Millisecond,
	}

	client, err := clientv3.New(config)
	if err != nil {
		return err
	}

	kv := clientv3.NewKV(client)
	lease := clientv3.NewLease(client)

	G_JobMgr = &JobManager{
		client: client,
		kv:     kv,
		lease:  lease,
	}

	return nil
}

// 保存任务
func (jobMgr *JobManager) SaveJob(job *common.Job) (oldJob *common.Job, err error) {
	jobKey := "/cron/jobs/" + job.Name

	bytes, err := json.Marshal(job)
	if err != nil {
		return
	}

	// 保存到etcd
	putResponse, err := jobMgr.kv.Put(context.TODO(), jobKey, string(bytes), clientv3.WithPrevKV())

	if err != nil {
		return nil, err
	}

	if putResponse.PrevKv != nil {
		err := json.Unmarshal(putResponse.PrevKv.Value, &oldJob)
		if err != nil {
			return oldJob, nil
		}
	}

	return
}

// 删除任务
